package com.huilian.iotbox.data.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.config.Config;
import com.huilian.iotbox.data.dto.MyBankPhotoDto;
import com.huilian.iotbox.data.enums.BaiduImageStatusEnum;
import com.huilian.iotbox.data.enums.PhotoType;
import com.huilian.iotbox.data.exception.ControllerException;
import com.huilian.iotbox.data.exception.SysException;
import com.huilian.iotbox.data.properties.ImageProperties;
import com.huilian.iotbox.data.properties.QiniuProperties;
import com.huilian.iotbox.data.service.BaiduApiService;
import com.huilian.iotbox.data.service.UploadService;
import com.huilian.iotbox.data.utils.Util;
import com.jcraft.jsch.ChannelSftp;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Region;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;


/**
 * @author 谢洛涛
 * @date 2021/3/16 17:57
 */
@Slf4j
@Service
public class UploadServiceImpl implements UploadService {
    @Autowired
    private QiniuProperties qiniuProperties;
    @Autowired
    private BaiduApiService baiduApiService;
    @Autowired
    private ImageProperties imageProperties;

    @Override
    public ServerResponse uploadQiniu(MyBankPhotoDto myBankPhotoDto) throws Exception {
        try {

//            double fileSize = (double) myBankPhotoDto.getFile().getSize() / 1048576;
//            if (fileSize > 1) {
//                return ServerResponse.createByErrorMessage("图片不能大于1MB");
//            }
            Configuration cfg = new Configuration(Region.region2());               //zong1() 代表华南地区
            UploadManager uploadManager = new UploadManager(cfg);
            Auth auth = Auth.create(qiniuProperties.getAccessKey(), qiniuProperties.getSecretKey());

            String qiniuBucket = qiniuProperties.getBucket();

            String upToken = auth.uploadToken(qiniuBucket);

            String fileName = UUID.randomUUID().toString().replaceAll("-", "");
            //为了图片安全性推荐使用UUID
            String keyRes = fileName + ".jpg";
            Response response = uploadManager.put(myBankPhotoDto.getFile().getBytes(), keyRes, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            log.info("图片上传成功: {}", keyRes);
            try {
//                if (PhotoType.CERT_PHOTO_A.equals(myBankPhotoDto.getPhotoType())){
//                    String imgUrl = Config.imgUrl + fileName + ".jpg";
//                    JSONObject idCertNo = baiduApiService.getIdentityPeriod(imageBase,1);
//                    if(!BaiduImageStatusEnum.NORMAL.getCode().equals(idCertNo.get("imageStatus"))){
//                        throw new ControllerException(idCertNo.getString("msg"));
//                    }
//                    myBankPhotoDto.setPrincipalPerson(idCertNo.getString("name"));
//                    myBankPhotoDto.setPrincipalCertNo(idCertNo.getString("certNo"));
//                } else if(PhotoType.CERT_PHOTO_B.equals(myBankPhotoDto.getPhotoType())){
//                    String imgUrl = Config.imgUrl + fileName + ".jpg";
//                    JSONObject idCertNo = baiduApiService.getIdentityPeriod(imageBase,2);
//                    if(!BaiduImageStatusEnum.NORMAL.getCode().equals(idCertNo.get("imageStatus"))){
//                        throw new ControllerException(idCertNo.getString("msg"));
//                    }
//                    myBankPhotoDto.setPrincipalCertNoStartDate((String) idCertNo.get("staData"));
//                    myBankPhotoDto.setPrincipalCertNoExpDate((String) idCertNo.get("endData"));
//                }
//                else if (PhotoType.LICENSE_PHOTO.equals(myBankPhotoDto.getPhotoType())){
//                    String imgUrl = Config.imgUrl + fileName + ".jpg";
//                    JSONObject idCertNo = baiduApiService.getBusiness(fileName, imgUrl);
//                    if (StringUtils.isBlank((String) idCertNo.get("staData")) || "无".equals((String) idCertNo.get("staData"))) {
//                        throw new ControllerException("请上传清晰营业执照");
//                    }
//                    myBankPhotoDto.setLegalPerson(idCertNo.getString("businessName"));
//                    myBankPhotoDto.setBussStartDate(idCertNo.getString("staData"));
//                    String endData = null;
//                    if("无".equals(idCertNo.getString("endData"))){
//                        endData = "长期";
//                    }else{
//                        endData =idCertNo.getString("endData");
//                    }
//                    myBankPhotoDto.setBussExpDate(endData);
//                }else if(PhotoType.BANK_CARD_A.equals(myBankPhotoDto.getPhotoType())){
//                    String imgUrl = Config.imgUrl + fileName + ".jpg";
//                    JSONObject jsonBuss = baiduApiService.getBankCard(fileName, imgUrl);
//                    String bankCardNumber = (String) jsonBuss.get("bankCardNumber");
//                    if(StringUtils.isBlank(bankCardNumber) || "无".equals(bankCardNumber)){
//                        throw new ControllerException("请上传清晰结算银行卡正面");
//                    }
//                    myBankPhotoDto.setBankCardNumber(bankCardNumber);
//                    log.info("银行卡",myBankPhotoDto.getBankCardNumber());
//                }
            } catch (Exception e) {
                return ServerResponse.createByErrorMessage(e.getMessage());
            }
            myBankPhotoDto.setPicture(fileName);
            myBankPhotoDto.setFile(null);
            return ServerResponse.createBySuccess(myBankPhotoDto);

        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            return ServerResponse.createByErrorMessage("图片上传失败");
        } catch (IOException e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("图片上传失败");
        }
    }

    @Override
    public ServerResponse uploadImageToFTP(InputStream inputStream) {
        try {
//            String suffix = image.getOriginalFilename().substring(image.getOriginalFilename().lastIndexOf(".") + 1);
//            if(!(ImageSuffixEnum.BMP.getSuffix().equals(suffix.toUpperCase()) ||
//                    ImageSuffixEnum.GIF.getSuffix().equals(suffix.toUpperCase()) ||
//                    ImageSuffixEnum.JPEG.getSuffix().equals(suffix.toUpperCase()) ||
//                    ImageSuffixEnum.JPG.getSuffix().equals(suffix.toUpperCase()) ||
//                    ImageSuffixEnum.PNG.getSuffix().equals(suffix.toUpperCase()) ||
//                    ImageSuffixEnum.SVG.getSuffix().equals(suffix.toUpperCase()))){
//                return ServerResponse.createByErrorMessage("图片格式不正确");
//            }

            JSONObject result = new JSONObject();
            String newName = UUID.randomUUID().toString().replaceAll("-", "") + ".jpg";
            InputStream input = inputStream;

            ChannelSftp sftp = Util.ftpLogin(imageProperties.getHost(), imageProperties.getPort(), imageProperties.getUserName(),
                    imageProperties.getPassWord(), imageProperties.getBasePath());

            if (sftp == null) {
                return ServerResponse.createByErrorMessage("ftp登录失败");
            }
            sftp.put(input, newName);
            result.put("keyRes", newName);
            return ServerResponse.createBySuccess(result);
        } catch (Exception e) {
            return ServerResponse.createByErrorMessage("图片上传失败");
        }
    }

    /**
     * 按图片类型（身份证正面、反面、结算卡正面、反面等等）七牛图片上传
     *
     * @param myBankPhotoDto
     * @return
     */
    @Override
    public ServerResponse uploadQiNiuByType(MyBankPhotoDto myBankPhotoDto) {
        try {
            Configuration cfg = new Configuration(Region.region2());               //zong1() 代表华南地区
            UploadManager uploadManager = new UploadManager(cfg);
            Auth auth = Auth.create(qiniuProperties.getAccessKey(), qiniuProperties.getSecretKey());

            String qiNiuBucket = qiniuProperties.getBucket();
            String upToken = auth.uploadToken(qiNiuBucket);
            String fileName = UUID.randomUUID().toString().replaceAll("-", "");
            //为了图片安全性推荐使用UUID
            String keyRes = fileName + ".jpg";
            Response response = uploadManager.put(myBankPhotoDto.getFile().getBytes(), keyRes, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            log.info("图片上传成功: {}", keyRes);
            try {
                if (PhotoType.CERT_PHOTO_A.equals(myBankPhotoDto.getPhotoType())) {
                    String imgUrl = Config.imgUrl + fileName + ".jpg";
                    JSONObject idCertNo = baiduApiService.getIdentityPeriod(fileName, imgUrl, Integer.valueOf(PhotoType.CERT_PHOTO_A));
                    if (!BaiduImageStatusEnum.NORMAL.getCode().equals(idCertNo.get("imageStatus"))) {
                        throw new ControllerException(idCertNo.getString("msg"));
                    }
                    myBankPhotoDto.setPrincipalPerson(idCertNo.getString("name"));
                    myBankPhotoDto.setPrincipalCertNo(idCertNo.getString("certNo"));
                } else if (PhotoType.CERT_PHOTO_B.equals(myBankPhotoDto.getPhotoType())) {
                    String imgUrl = Config.imgUrl + fileName + ".jpg";
                    JSONObject idCertNo = baiduApiService.getIdentityPeriod(fileName, imgUrl, Integer.valueOf(PhotoType.CERT_PHOTO_B));
                    if (!BaiduImageStatusEnum.NORMAL.getCode().equals(idCertNo.get("imageStatus"))) {
                        throw new ControllerException(idCertNo.getString("msg"));
                    }
                    myBankPhotoDto.setPrincipalCertNoStartDate((String) idCertNo.get("staData"));
                    myBankPhotoDto.setPrincipalCertNoExpDate((String) idCertNo.get("endData"));
                } else if (PhotoType.LICENSE_PHOTO.equals(myBankPhotoDto.getPhotoType())) {
                    String imgUrl = Config.imgUrl + fileName + ".jpg";
                    JSONObject idCertNo = baiduApiService.getBusiness(fileName, imgUrl);
                    if (StringUtils.isBlank((String) idCertNo.get("staData")) || "无".equals((String) idCertNo.get("staData"))) {
                        throw new ControllerException("请上传清晰营业执照");
                    }
                    myBankPhotoDto.setLegalPerson(idCertNo.getString("businessName"));
                    myBankPhotoDto.setBussStartDate(idCertNo.getString("staData"));
                    String endData = null;
                    if ("无".equals(idCertNo.getString("endData"))) {
                        endData = "长期";
                    } else {
                        endData = idCertNo.getString("endData");
                    }
                    myBankPhotoDto.setBussExpDate(endData);
                } else if (PhotoType.BANK_CARD_A.equals(myBankPhotoDto.getPhotoType())) {
                    String imgUrl = Config.imgUrl + fileName + ".jpg";
                    JSONObject jsonBuss = baiduApiService.getBankCard(fileName, imgUrl);
                    String bankCardNumber = (String) jsonBuss.get("bankCardNumber");
                    if (StringUtils.isBlank(bankCardNumber) || "无".equals(bankCardNumber)) {
                        throw new ControllerException("请上传清晰结算银行卡正面");
                    }
                    myBankPhotoDto.setBankCardNumber(bankCardNumber);
                    log.info("银行卡", myBankPhotoDto.getBankCardNumber());
                }
            } catch (Exception e) {
                return ServerResponse.createByErrorMessage(e.getMessage());
            }
            myBankPhotoDto.setPicture(fileName);
            myBankPhotoDto.setFile(null);
            return ServerResponse.createBySuccess(myBankPhotoDto);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            return ServerResponse.createByErrorMessage("图片上传失败");
        } catch (IOException e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("图片上传失败");
        }
    }

    @Override
    public JSONObject imgVad(String imgName, String imgUrl, Integer type) throws IOException {
        if (type == 1 || type == 2) {
            try {
                JSONObject json = baiduApiService.getIdentityPeriod(imgName, imgUrl, type);
                if (type == 1 && !BaiduImageStatusEnum.NORMAL.getCode().equals(json.get("imageStatus"))) {
                    throw new SysException(json.getString("msg"));
                }
                if (type == 2 && !BaiduImageStatusEnum.NORMAL.getCode().equals(json.get("imageStatus"))) {
                    throw new SysException(json.getString("msg"));
                }
                return json;
            } catch (SysException e) {
                throw new SysException(e.getMessage());
            }
        }
        if (type == 3) {
            try {
                JSONObject jsonBuss = baiduApiService.getBusiness(imgName, imgUrl);
                String staData = (String) jsonBuss.get("staData");
                if (StringUtils.isBlank(staData) || "无".equals(staData)) {
                    throw new SysException("请上传清晰营业执照");
                }
                return jsonBuss;
            } catch (Exception e) {
                throw new SysException("请上传清晰营业执照");
            }
        }
        if (type == 13) {
            JSONObject jsonBuss = baiduApiService.getBankCard(imgName, imgUrl);
            String bankCardNumber = (String) jsonBuss.get("bankCardNumber");
            if (StringUtils.isBlank(bankCardNumber) || "无".equals(bankCardNumber)) {
                throw new SysException("请上传清晰结算银行卡正面");
            }
            return jsonBuss;
        }
        return null;
    }

    @Override
    public ServerResponse deleteByFileNameToFTP(String fileName) {

        try {
            ChannelSftp sftp = Util.ftpLogin(imageProperties.getHost(), imageProperties.getPort(), imageProperties.getUserName(),
                    imageProperties.getPassWord(), imageProperties.getBasePath());

            if (sftp == null) {
                return ServerResponse.createByErrorMessage("ftp登录失败");
            }

            sftp.rm(fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMessage("删除文件失败");
        }

        return ServerResponse.createBySuccess();
    }

}
